/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.awwork.lr.checker.views;

import com.awwork.lr.checker.beans.Result;
import com.awwork.lr.checker.tools.HTMLReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.SwingWorker;

/**
 *
 * @author machao
 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }
    private List<String> websites = null;
    private Task task = null;
    ResultDialog dialog = new ResultDialog(this, false);

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        showPanel1 = new javax.swing.JTextArea();
        doCheck = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        showPanel2 = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        address = new javax.swing.JTextField();
        jProgressBar1 = new javax.swing.JProgressBar();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentsMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        showPanel1.setColumns(20);
        showPanel1.setRows(5);
        jScrollPane2.setViewportView(showPanel1);

        doCheck.setText("开始检查");
        doCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doCheckActionPerformed(evt);
            }
        });

        jLabel2.setText("检查详情");

        showPanel2.setEditable(false);
        showPanel2.setColumns(20);
        showPanel2.setRows(5);
        jScrollPane1.setViewportView(showPanel2);

        jLabel3.setText("链接地址：");

        address.setText("chine-evasion.com");
        address.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addressActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane1)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(address))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 332, Short.MAX_VALUE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(doCheck)
                        .addGap(18, 18, 18)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(doCheck)
                        .addGap(14, 14, 14))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)))
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        fileMenu.setMnemonic('f');
        fileMenu.setText("文件");

        openMenuItem.setMnemonic('o');
        openMenuItem.setText("加载");
        openMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openMenuItem);

        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("退出");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setMnemonic('h');
        helpMenu.setText("帮助");

        contentsMenuItem.setMnemonic('c');
        contentsMenuItem.setText("说明");
        contentsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                contentsMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(contentsMenuItem);

        aboutMenuItem.setMnemonic('a');
        aboutMenuItem.setText("关于");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed
        //建立文件选择框对象 
        JFileChooser fc = new JFileChooser();
        //设定文件选择框标题 
        fc.setDialogTitle("打开网址文件");
        //显示文件选择框，在选择后将结果储存到returnVal变量中 
        int returnVal = fc.showOpenDialog(null);
        //如果用户选择了文件，并点击了"Opne/打开"按钮，显示用户选择的文件全名路径，
        //如果用户点击"Close/关闭"按钮，以及其它方式退出文件选择框，则什么也不做。   
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            this.showPanel1.setText(null);
            websites = this.getWebsiteListFromTxt(file);

            Iterator<String> it = websites.iterator();
            while (it.hasNext()) {
                String website = it.next();
                if (!"".equals(website.trim())) {
                    this.showPanel1.append(website + "\n");
                }
            }
        }
    }//GEN-LAST:event_openMenuItemActionPerformed

    private void doCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doCheckActionPerformed

        if (null == websites || websites.size() == 0) {
            try {
                websites = new ArrayList<String>();
                BufferedReader br = new BufferedReader(new StringReader(this.showPanel1.getText()));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    if (!"".equals(line.trim())) {
                        websites.add(line.trim());
                    }
                }
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Iterator<String> it = websites.iterator();
        this.jProgressBar1.setMinimum(0);
        this.jProgressBar1.setMaximum(websites.size());
        task = new Task();
        task.itwebsites = it;
        task.execute();
    }//GEN-LAST:event_doCheckActionPerformed

    private void addressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addressActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_addressActionPerformed

    private void contentsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_contentsMenuItemActionPerformed
        ContentDialog content = new ContentDialog(this, true);
        content.setTitle("说明");
        content.setVisible(true);
    }//GEN-LAST:event_contentsMenuItemActionPerformed

    private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
        AboutDialog about = new AboutDialog(this, true);
        about.setTitle("关于");
        about.setVisible(true);
    }//GEN-LAST:event_aboutMenuItemActionPerformed

    /**
     * 检查网页是否包含链接
     *
     * @param website 网页
     * @param subString 链接
     * @param type 检查类型 1常规，2noxxx
     * @return 是否包含
     */
    private Result checkWebsite(String website, String subString, String type) {
        long starttime = 0;
        starttime = new Date().getTime();
        String html = HTMLReader.readHTML3(website, "UTF-8");
        
        this.showPanel2.append("-------- download " + website + " done! used " + (new Date().getTime() - starttime) + "ms \n");
        starttime = new Date().getTime();
        Result r = null;
        r = new Result();
        if (html.indexOf(subString) == -1) {
            r.setWebsite(website);
            if ("".equals(html.trim())) {
                r.setHasLink("链接失败");
            } else {
                r.setHasLink("false");
            }
        } else {
            r.setWebsite(website);
            r.setHasLink("true");
            r.setAtag(HTMLReader.getAtag(html, subString));
            r.setHref(HTMLReader.getHref(r.getAtag()));
            r.setText(HTMLReader.getText(r.getAtag()));
            r.setNofollow(HTMLReader.getNofollow(r.getAtag()));
            r.setAnumber(HTMLReader.getAtagFromText(html, subString, 1500, "<a "));
        }
        this.showPanel2.append("-------- analyse " + website + " done! used " + (new Date().getTime() - starttime) + "ms \n");
        return r;
    }

    /**
     * 从文本文件中读取网址列表
     *
     * @param file
     * @return List<String>
     */
    private List<String> getWebsiteListFromTxt(File file) {
        List<String> result = null;
        try {
            result = new ArrayList<String>();
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                result.add(line.trim());
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    class Task extends SwingWorker<Void, Void> {

        Iterator<String> itwebsites = null;

        @Override
        public Void doInBackground() {
            ResultDialog.resultlist = new ArrayList<Result>();
            jProgressBar1.setStringPainted(true);
            while (itwebsites.hasNext()) {

                String website = itwebsites.next();
                CheckWorker worker = new CheckWorker();
                worker.website = website;
                worker.execute();

            }
            return null;
        }

        @Override
        public void done() {
            System.out.println("task done!");
            //dialog.setResultList(checkresults);
            //dialog.updateTable(null);
            //dialog.setVisible(true);
        }
    }

    class Task2 extends SwingWorker<Void, Void> {

        Iterator<String> itwebsites = null;
        List<Result> list = new ArrayList<Result>();

        @Override
        public Void doInBackground() {
            int progress = 0;
            setProgress(0);
            while (itwebsites.hasNext()) {
                setProgress(progress);
                jProgressBar1.setStringPainted(true);
                String website = itwebsites.next();
                showPanel2.append("----- Starting check: " + website + "\n");
                Result r = checkWebsite(website, address.getText(), null);
                list.add(r);
                showPanel2.append("----- check finish! \n");
                progress++;
                jProgressBar1.setValue(progress);
            }
            return null;
        }

        @Override
        public void done() {
            dialog.setResultList(list);
            dialog.updateTable(null);
            dialog.setVisible(true);
        }
    }

    class CheckWorker extends SwingWorker<Result, Void> {

        String website = null;

        @Override
        public Result doInBackground() {
            Result r = null;
            if (null != website) {
                showPanel2.append("----- Starting check: " + website + "\n");
                r = checkWebsite(website, address.getText(), null);
                showPanel2.append("----- check finish! \n");
            }
            return r;
        }

        @Override
        public void done() {
            try {
                Result r = get();
                //System.out.println(jProgressBar1.getValue() + " , " + websites.size() + " , "  + r.getWebsite());
                
                if (null != r) {
                    
                }
                jProgressBar1.setValue(jProgressBar1.getValue() + 1);
                ResultDialog.resultlist.add(r);
                
                if (jProgressBar1.getValue() == websites.size()) {
                    dialog.setResultList(ResultDialog.resultlist);
                    dialog.updateTable(null);
                    dialog.setVisible(true);
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                
            }

        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JTextField address;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JButton doCheck;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JTextArea showPanel1;
    private javax.swing.JTextArea showPanel2;
    // End of variables declaration//GEN-END:variables
}
